<template>
  <el-dialog v-if="isOpen" class="dia-style" :title="title" :visible.sync="isOpen" width="80%">
    <el-form ref="elForm" :model="formData" :rules="rules" size="medium" label-width="100px" label-position="left" @submit.native.prevent>
      <el-form-item label="字段名称" prop="fieldName">
        <el-input
          v-model="formData.fieldName"
          placeholder="请输入字段名称"
          clearable
          :style="{ width: '100%' }"
          maxlength="150"
          @change="handleChange($event, formData)"
        />
      </el-form-item>
      <el-form-item label="引用字段" prop="citeField">
        <el-select
          v-model="formData.citeField"
          filterable
          placeholder="请选择字段类型"
          clearable
          :style="{ width: '100%' }"
          @change="handleCiteField"
        >
          <el-option
            v-for="(item, index) in referenceFieldList"
            :key="index"
            :label="item.columnName"
            :value="item.columnName"
          />
        </el-select>
      </el-form-item>
      <el-form-item v-if="formData.citeField == '自定义'" label="字段类型" prop="fieldType">
        <el-select
          v-model="formData.fieldType"
          filterable
          placeholder="请选择字段类型"
          clearable
          :style="{ width: '100%' }"
          @change="handleFieldType"
        >
          <el-option
            v-for="(item, index) in fieldTypeOptions"
            :key="index"
            :label="item.customName"
            :value="item.customVaue"
          />
        </el-select>
      </el-form-item>
      <el-form-item v-show="formData.citeField && formData.citeField != '自定义'" label="转换类型" prop="type">
        <convert-type
          ref="converTypeRef"
          :product-code="productCode"
          :param-value="citeFieldValue"
          :echo-data="{ convertTypeEchoData: convertTypeEchoData }"
          :echo-rule-method-list="ruleMethodList"
        />
      </el-form-item>
      <template v-if="formData.citeField == '自定义'">
        <!--    自定义类型6    -->
        <el-form-item v-if="customType == '6'">
          <fieldCustom
            ref="custom6Ref"
            :name-list="nameList"
            :context-list="contextList"
            :table-data="tableData"
            :echo-data="{
              custom6EchoData: custom6EchoData,
              ruleExpress: ruleExpress,
            }"
            :is-edit="isEdit"
          />
        </el-form-item>
        <!--   自定义-特殊文本    -->
        <el-form-item v-if="customType == '5'" label="描述信息">
          <el-row>
            <el-col :span="21">
              <vue-tribute :options="tributeOptions">
                <textarea id="textarea" rows="5" placeholder="输入$可快速引用参考字段" @input="valueChange" />
              </vue-tribute>
            </el-col>
            <el-col :span="2" style="margin-left: 20px">
              <el-button @click="handleCheck">校验</el-button>
            </el-col>
            <el-col v-if="isShow" :span="24">
              <span class="message-box success">{{ formData.message }}</span>
            </el-col>
          </el-row>
        </el-form-item>
      </template>
    </el-form>
    <div slot="footer">
      <el-button type="primary" @click="handleConfirm">保存</el-button>
      <el-button @click="close">取消</el-button>
    </div>
  </el-dialog>
</template>
<script>
import ConvertType from './ruleFieldConvert'
import fieldCustom from './ruleFieldCustom'
import VueTribute from 'vue-tribute'
import { getCustomList, getCustomDictList, checkDataColumnRule } from '@/api/milkyway/accessRules'
import { deepClone } from '@/utils/index'

export default {
  components: { ConvertType, fieldCustom, VueTribute },
  inheritAttrs: false,
  props: {
    title: {
      type: String,
      default() {
        return '编辑'
      }
    },
    productCode: {
      type: String,
      default() {
        return ''
      }
    },
    tableData: {
      type: Array,
      default() {
        return []
      }
    },
    contextList: {
      type: Array,
      default() {
        return []
      }
    },
    descList: {
      type: Array,
      default() {
        return []
      }
    },
    dataForm: {
      type: Object,
      default() {
        return {}
      }
    }
  },
  data() {
    return {
      isEdit: false,
      isCheck: false,
      editIndex: 0,
      isShow: false,
      // 输入的${}值
      stringArr: [],
      // 引用字段下拉框数据
      referenceFieldList: [],
      customList: [{ columnName: '自定义', columnValue: '自定义' }],
      isOpen: false,
      formData: {
        citeField: '自定义'
      },
      rules: {
        fieldName: [
          {
            required: true,
            message: '请输入字段名称',
            trigger: 'blur'
          },
          { validator: this.checkDuplicateName, trigger: 'blur' }
        ],
        citeField: [
          {
            required: true,
            message: '请输入引用字段',
            trigger: 'blur'
          }
        ],
        fieldType: [
          {
            required: true,
            message: '请选择字段类型',
            trigger: 'change'
          }
        ]
      },
      tributeOptions: {
        trigger: '$',
        requireLeadingSpace: false,
        allowSpaces: false,
        // 为替换文本指定自定义后缀
        replaceTextSuffix: ' ',
        noMatchTemplate: '<li class="empt">暂无数据</li>',
        values: [],
        // checkValue: [],
        positionMenu: true,
        menuContainer: document.querySelector('.menu-container'),
        selectTemplate: function(item) {
          /* return (
            '<span contenteditable="false" class="text-name"><a>${' + item.original.key + '}</a></span><span class="text-value" style="display:none">' + item.original.value + '</span>'
          )*/
          return `\$\{${item.original.key}\}`
        }
      },
      // 字段类型list
      fieldTypeOptions: [],
      // 选中的字段类型
      customType: '',
      nameList: [],
      //   提交的字段格式 -- 方法
      ruleMethodList: [],
      //   提交的字段格式 -- 规则
      ruleExpress: [],
      //  引用类型value值
      citeFieldValue: '',
      // 回显的表单项
      echoData: {},
      //   custom6回显数据
      custom6EchoData: {},
      //  转换类型回显数据
      convertTypeEchoData: {},
      dialogData: {}
    }
  },
  watch: {
    tableData: {
      handler(newVal) {
        if (newVal && newVal != null) {
          this.referenceFieldList = this.customList.concat(newVal)
          // "key,value"
          // this.tributeOptions.values = newVal.map((i) => {
          //   return { key: i.columnName, value: i.columnValue }
          // })
          this.tributeOptions.values = this.descList.map(i => {
            return { key: i.label, value: i.value }
          })
        }
      },
      immediate: true,
      deep: true
    },
    dialogData: {
      handler(newVal) {
        if (newVal.formData) {
          console.log('dialogData监听-----', newVal)
          this.formData = newVal.formData
          this.custom6EchoData = newVal.custom6EchoData
          this.convertTypeEchoData = newVal.convertTypeEchoData
          this.ruleMethodList = newVal?.ruleMethodList
          this.ruleExpress = newVal?.dialogEchoDataRule?.ruleExpress
          if (this.formData?.fieldType) {
            const currentData = this.fieldTypeOptions.filter((i) => {
              return i.customVaue == this.formData.fieldType
            })
            this.customType = currentData[0].customType
          }
          if (this.customType == '6') {
            getCustomDictList({
              dictId: this.formData.fieldType,
              productCode: this.productCode
            }).then((res) => {
              this.nameList = res
            })
          }
          this.$nextTick(() => {
            if (this.formData?.paramValue && document.querySelector('#textarea')) {
              document.querySelector('#textarea').value = this.formData?.paramValue
            }
          })
        }
      },
      immediate: true,
      deep: true
    }
  },
  mounted() {
    this.getCustomList()
  },
  methods: {
    show(type, index) {
      this.reset()
      this.isOpen = true
      if (type == 'edit') {
        this.isEdit = true
        this.editIndex = index
      } else {
        this.isEdit = false
        this.ruleMethodList = []
      }
    },
    close() {
      this.isOpen = false
      this.isEdit = false
      this.editIndex = 0
      // this.dialogData = {}
      this.$refs['elForm'].resetFields()
      this.customType = ''
      this.isShow = false
    },
    // 表单重置
    reset() {
      this.isOpen = false
      this.isShow = false
      this.isEdit = false
      this.editIndex = 0
      // this.dialogData ={}
      this.customType = ''
      this.formData = {
        citeField: '自定义',
        fieldName: '',
        fieldType: '',
        description: ''
      }
      this.resetForm('elForm')
    },
    /** 点击保存按钮，校验 */
    handleConfirm() {
      this.$refs['elForm'].validate((valid) => {
        if (valid) {
          if (this.formData.citeField != '自定义') {
            this.$refs.converTypeRef.handleSubmit().then((res) => {
              this.formData.message = res.formData.list[res.formData.list.length - 1].message
              this.$emit('handleSubmit', {
                formData: this.formData,
                ruleMethodList: res.ruleMethodList,
                convertTypeEchoData: res.formData,
                isEdit: this.isEdit,
                editIndex: this.editIndex
              })
              this.isOpen = false
            })
          }
          if (this.formData.citeField == '自定义') {
            if (this.customType == '4') {
              this.$emit('handleSubmit', {
                formData: this.formData,
                ruleMethodList: this.ruleMethodList,
                isEdit: this.isEdit,
                editIndex: this.editIndex
              })
              this.isOpen = false
            }
            if (this.customType == '5') {
              if (this.isCheck) {
                this.$emit('handleSubmit', {
                  formData: this.formData,
                  ruleMethodList: this.ruleMethodList,
                  isEdit: this.isEdit,
                  editIndex: this.editIndex
                })
                this.isOpen = false
                this.isCheck = false
              } else {
                this.$message.error('请校验描述信息!')
              }
            }
            if (this.customType == '6') {
              this.$refs.custom6Ref.handleSubmit().then((res) => {
                const query = {
                  columnName: this.formData.fieldName,
                  columnValue: '',
                  columnType: this.formData.fieldType,
                  columnConvert: this.formData.citeField,
                  ruleExpress: res.formData.list,
                  ruleMethodList: [],
                  metaName: ''
                }
                checkDataColumnRule({ dataColumnRuleList: query }).then((response) => {
                  this.formData.message = response
                  this.$emit('handleSubmit', {
                    formData: this.formData,
                    dialogEchoDataRule: res,
                    custom6EchoData: res.formData,
                    isEdit: this.isEdit,
                    editIndex: this.editIndex,
                    ruleExpress:res.formData.list
                  })
                  this.isOpen = false
                })
              })
            }
          }

          // this.$emit('handleSubmit', this.formData)
        } else if (!valid) return
      })
    },
    /**  描述信息触发的事件  */
    valueChange(e) {
      this.isShow = false
      this.formData.paramValue = e.target.value.replace(/\s/g, '')
      document.getElementById('textarea').value = this.formData.paramValue
      this.ruleMethodList[0].paramValue = JSON.stringify([this.formData.fieldType, this.formData.paramValue])
    },
    /**  校验 */
    handleCheck() {
      this.formData.message = this.formData.paramValue
      const arr = this.getExecStrs(this.formData.paramValue)
      let newValue = this.formData.paramValue
      if (arr.length > 0) {
        arr.forEach((item, index) => {
          this.tributeOptions.values.forEach((i) => {
            if (i.key == item.value) {
              newValue = newValue.replaceAll(item.str, i.value)
            }
          })
          this.formData.message = newValue
        })
        this.isShow = true
      } else if (this.formData.paramValue) {
        this.isShow = true
        this.formData.message = this.formData.paramValue
      }
      this.isCheck = true
    },
    /** 筛选字符串的值 */
    getExecStrs(str) {
      const reg = /\$\{(.+?)\}/g
      const list = []
      let result = null
      do {
        result = reg.exec(str)
        result && list.push({ str: result[0], value: result[1] })
      } while (result)
      return list
    },
    /** 获取自定义的字段类型 */
    getCustomList() {
      getCustomList(this.productCode).then((res) => {
        this.fieldTypeOptions = res
      })
    },
    /** 选择字段类型*/
    handleFieldType(value) {
      this.isCheck = false
      const currentData = this.fieldTypeOptions.filter((i) => {
        return i.customVaue == value
      })
      this.customType = currentData[0].customType
      if (this.customType == '5') {
        this.ruleMethodList = [
          {
            paramValue: '',
            ruleGroup: 'DataMappingHandle',
            ruleMethod: 'getDateMap'
          }
        ]
      } else if (this.customType == '4') {
        this.ruleMethodList = [
          {
            paramValue: '',
            ruleGroup: 'UUID',
            ruleMethod: 'toUUID'
          }
        ]
      }
      //  获取自定义-字段类型-名称下拉框
      getCustomDictList({ dictId: value, productCode: this.productCode }).then((res) => {
        this.nameList = res
        this.custom6EchoData = {
          list: [
            {
              contextValue: '',
              operators: '',
              relationData: { flag: 'and', subSyntaxExpressnList: [] }
            }
          ]
        }
      })
    },
    // 表单项值改变时
    handleChange(value, formData) {},
    /**  字段名称校验 */
    checkDuplicateName(rule, value, callback) {
      if (value) {
        const isDuplicate = this.tableData.every((i) => {
          return i.columnName != value
        })
        if (!isDuplicate && !this.isEdit) {
          return callback(new Error('字段名称重复，请修改'))
        } else {
          callback()
        }
      }
    },
    /** 选择引用字段*/
    handleCiteField(value) {
      const currentData = this.referenceFieldList.filter((i) => {
        return i.columnName == value
      })
      this.citeFieldValue = currentData[0]?.columnValue
      if (value != '自定义') {
        this.convertTypeEchoData = {
          list: {
            contextValue: '',
            operators: '',
            relationData: { flag: 'and', subSyntaxExpressnList: [] }
          }
        }
      }
    },
    /** 编辑回显数据*/
    handleEchoData(data) {
      this.dialogData = deepClone(data)
      this.citeFieldValue = ''
      if (data.formData.citeField == '自定义' && data.formData.paramValue && data.formData.message) {
        this.isShow = true
      }
      this.handleCiteField(data.formData.citeField)
    }
  }
}
</script>
<style lang="scss" scoped>
.el-dialog {
  z-index: 3000;
}

.message-box {
  display: inline-block;
  width: 100%;
  min-height: 36px;
  margin: 10px auto 0;
  padding: 0 10px;
  border-radius: 4px;

  &.success {
    background-color: #e7faf0;
    border-color: #d0f5e0;
    color: #13ce66;
  }
}
.v-tribute {
  textarea {
  }
}
.v-tribute textarea {
  width: 95%;
  border: 1px solid #dcdfe6;
}
</style>
